import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/ui/user/Invite4.dart';
import 'package:fate_blind_box/ui/user/institution/IntegralInstition.dart';
import 'package:fate_blind_box/ui/user/institution/institution.dart';
import 'package:fate_blind_box/ui/user/institution/registerinstitution.dart';
import 'package:fate_blind_box/ui/user/matchMaker/payFailDialog.dart';
import 'package:fate_blind_box/ui/user/profile.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/material.dart';
import '../../../main222.dart';
import '../../../theme/theme_color.dart';
import '../authentication/authentication.dart';
import 'maker_manager.dart';


// class loveMakerUI extends StatelessWidget {
//   final String typeTitle;
//   const loveMakerUI(this.typeTitle, {Key? key}) : super(key: key);
//
//   @override
//   Widget build(BuildContext context) {
//     return const loveMakerUIWidget();
//   }
// }

class loveMakerUIWidget extends StatefulWidget {
  final String typeTitle;
  const loveMakerUIWidget(this.typeTitle, {Key? key}) : super(key: key);

  @override
  State<loveMakerUIWidget> createState() => loveMakerUIWidgetState();
}

class loveMakerUIWidgetState extends State<loveMakerUIWidget> {

  final List _listData = [{'img':'images/ic_fuliM.png','title':'福利',"sub":'1.爱心红娘权益 长期有效\n2.推荐粉丝，享受现金推广奖励\n3.粉丝推荐粉丝，享受积分推广奖励','height':124.0},
    {'img':'images/ic_fensiM.png','title':'粉丝数量',"sub":'拥有50名粉丝','button':'去邀请','height':80.0},
    // {'img':'images/ic_shiming.png','title':'实名认证',"sub":'','button':'去认证','height':60.0},
  ];

  final List _listDataBuss = [{'img':'images/ic_fuliM.png','title':'福利',"sub":'1.普通红娘权益 长期有效\n2.推荐粉丝，享受现金推广奖励\n3.粉丝推荐粉丝，享受积分推广奖励\n4.在吃喝玩乐及单身驿站战士，平台公开发布活动，活动有推送功能（推送功能限制次数）','height':165.0},
    {'img':'images/ic_fensiM.png','title':'营业执照',"sub":'','button':'去上传','height':50.0},
    // {'img':'images/ic_shiming.png','title':'实名认证',"sub":'','button':'去认证','height':60.0},
  ];

  int license = -1;
  int fans = 0;
  int makerType = 0;


  @override
  void initState() {
    super.initState();

    if(widget.typeTitle == '个人红娘'){
      makerType = 1;
      // _getFansNumberData();
    }else if(widget.typeTitle == '商家红娘'){
      makerType = 2;
    }

    _getFansNumberAndAgencyData();

  }

  //查询粉丝数量和营业执照
  void _getFansNumberAndAgencyData(){
    loading(() async{
      final res = await Api.getInstance().checkAgency();
      if(res['code'] == 0){
        setState(() {
          fans = res['data']['fansNumber'];
          license = res['data']['license'];
        });
      }
    });
  }


  //查询粉丝数量
  void _getFansNumberData(){
    loading(() async{
      final res = await Api.getInstance().checkFansNumber();
      if(res['code'] == 0){
        setState(() {
          fans = res['data']['fansNumber'];
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return AppWidget.navTitleBar(
      bgColor: const Color(0xFFF9F9F9),
      title:widget.typeTitle == '个人红娘' ? "爱心红娘" : "普通红娘",
      childWidget:Column(
        children: [
          SizedBox(
            height: size.height - 190,
            child: ListView.builder(
              itemBuilder: (_, index) {
                return widget.typeTitle == '个人红娘' ? _buildItems(_listData?[index], index) : _buildItems(_listDataBuss?[index], index);
              },
              itemCount:widget.typeTitle == '个人红娘' ? _listData.length : _listDataBuss.length,
            ),
          ),

          // Expanded(child: Container()),
          // Container(
          //     color: Colors.white,
          //     margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),
          //
          //     height: 84,
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceAround,
          //       crossAxisAlignment: CrossAxisAlignment.start,
          //       children: [
          //         Container(
          //           alignment: Alignment.center,
          //           margin: const EdgeInsets.fromLTRB(10, 20, 10, 0),
          //           padding: const EdgeInsets.symmetric(vertical: 10),
          //           height: 45,
          //           width: size.width -80,
          //           decoration: ShapeDecoration(
          //             shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22.5)),
          //             color: const Color(0xFF7F69D9),
          //           ),
          //
          //           child: const Text('确认申请红娘',style: TextStyle(color: Colors.white,fontSize: 16),),
          //         ),
          //       ],
          //     )
          // ),
          Align(
            alignment: Alignment.center,
            child: Container(
                color: Colors.white,
                margin: const EdgeInsets.fromLTRB(0, 0, 0, 0),

                height: 84,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: (){

                        if(widget.typeTitle == '个人红娘'){
                          if(fans >= 50){
                            _applyLoveMaker();
                          }else {
                            toast('粉丝数量不足50，请先满足条件');
                          }
                        }else {
                          if(license == 1){
                            _applyNormalMaker();
                          }else {
                            toast('请先上传营业执照');
                          }

                        }

                        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const MakerManagerPage()));
                      },
                      child: Container(
                        alignment: Alignment.center,
                        margin: const EdgeInsets.fromLTRB(10, 20, 10, 0),
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        height: 45,
                        width: size.width -80,
                        decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22.5)),
                          color: const Color(0xFF7F69D9),
                        ),

                        child: const Text('确认申请红娘',style: TextStyle(color: Colors.white,fontSize: 16),),
                      ),
                    ),
                  ],
                )
            ),
          ),
        ],
      )
    );
  }

  //申请商家--普通红娘
  void _applyNormalMaker(){
    loading(() async{
      final res = await Api.getInstance().applyBusinessMatch(Provider.memberId);
      if(res['code'] == 0){
        Navigator.of(navKey.currentState!.overlay!.context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => institutionUi('1')), (route) => route == null);
      }else {
        toast(res['msg']);
      }
    });
  }

  //申请个人--爱心红娘
  void _applyLoveMaker(){
    loading(() async{
      final res = await Api.getInstance().applyLoveMaker(fans, 1, makerType);
      if(res['code'] == 0){
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const MakerManagerPage('2')));
        Navigator.of(navKey.currentState!.overlay!.context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => const MakerManagerPage('1')), (route) => route == null);
      }else {
        toast(res['msg']);
      }
    });
  }



  @override
  _buildItems(Map map, int index) {
    return GestureDetector(
      onTap: () {

      },
      child:Container(

        height: map['height'] ?? '',
        margin: const EdgeInsets.fromLTRB(15, 10, 15, 0),
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
          color: Colors.white,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [

            Expanded(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 14),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text.rich(
                      TextSpan(

                        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
                        children: [
                          WidgetSpan(
                            child: Image.asset(map['img'],width: 16,height: 16,),
                          ),

                          TextSpan(

                            text: '  ' + map["title"],
                          ),
                        ],
                      ),
                    ),
                    map["sub"].toString().isNotEmpty ? const SizedBox(height: 3,) : const SizedBox(height: 0,),
                    map["sub"].toString().isNotEmpty ?Text(
                      map["sub"] ?? "",
                      style: TextStyle(
                        color: ThemeColor.checkNormalColor,
                        fontSize: 11,),
                    ):const SizedBox(),

                  ],
                ),
              ),
            ),

            GestureDetector(
              onTap: () async{
                if(widget.typeTitle == '个人红娘' && fans < 50){
                  _onTap(index);
                }else if(widget.typeTitle == '商家红娘' && license <= 0){
                  _onTapAgency(index);
                }
                // final result = await Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const CyclePublishUi()));
              },
              child: index != 0 ? Container(
                height: widget.typeTitle == '个人红娘' ? 32 : 28,
                margin: const EdgeInsets.only(right: 8),
                decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: widget.typeTitle == '个人红娘' ? fans < 50  ? ThemeColor.appColor : const Color(0xFFF8F8F8)
                                                      : license <= 0 ? ThemeColor.appColor : const Color(0xFFF8F8F8)
                ),
                alignment: Alignment.center,
                padding: const EdgeInsets.symmetric(horizontal: 12),
                child: widget.typeTitle == '个人红娘' ? Text(fans < 50 ? '去邀请' : '已完成', style: TextStyle(color: fans < 50 ? Colors.white : const Color(0xFFAAAAAA),fontSize: 14),)
                                                    : Text(license <= 0 ? '去上传' : '已完成', style: TextStyle(color: license <= 0 ? Colors.white : const Color(0xFFAAAAAA),fontSize: 14),),
              ):Container(),
            ),
          ],
        ),
      ),
    );
  }

  //上传营业执照
  _onTapAgency(int index){
    // Navigate.toPage(registerInstitionUI('ggggg'));
    Navigator.of(context).push(MaterialPageRoute(builder: (builder) => registerInstitionUI('nnn'))).then((value) => _getFansNumberAndAgencyData());
  }

  //邀请好友
  _onTap(int index){
    if(index == 1){
      Navigate.toPage(const Invite4Ui());
    } else if(index == 2) {
      Navigator.of(context).push(MaterialPageRoute(builder: (builder) => AuthenticationUI()));
    } else {


    }
    // paySucDialog.showPayDialog(context);
    // payFaiDialog.showPayDialog(context);

  }

}


